package com.cyzy.homework.controller;

import com.cyzy.homework.entity.Message;
import com.cyzy.homework.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 消息控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/messages")
@CrossOrigin(origins = "*")
public class MessageController {
    
    @Autowired
    private MessageService messageService;
    
    /**
     * 发送消息
     */
    @PostMapping("/send")
    public ResponseEntity<Map<String, Object>> sendMessage(@RequestBody Map<String, Object> request) {
        try {
            String fromUserId = (String) request.get("fromUserId");
            String fromUser = (String) request.get("fromUser");
            String toUserId = (String) request.get("toUserId");
            String title = (String) request.get("title");
            String content = (String) request.get("content");
            String type = (String) request.get("type");
            String level = (String) request.get("level");
            String extraData = (String) request.get("extraData");
            
            Message message = messageService.sendMessage(fromUserId, fromUser, toUserId, 
                                                        title, content, type, level, extraData);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "消息发送成功");
            response.put("data", message);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("发送消息失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "发送消息失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
    
    /**
     * 发送系统消息
     */
    @PostMapping("/system")
    public ResponseEntity<Map<String, Object>> sendSystemMessage(@RequestBody Map<String, Object> request) {
        try {
            String toUserId = (String) request.get("toUserId");
            String title = (String) request.get("title");
            String content = (String) request.get("content");
            String level = (String) request.get("level");
            
            Message message = messageService.sendSystemMessage(toUserId, title, content, level);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "系统消息发送成功");
            response.put("data", message);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("发送系统消息失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "发送系统消息失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
    
    /**
     * 发送欢迎消息
     */
    @PostMapping("/welcome")
    public ResponseEntity<Map<String, Object>> sendWelcomeMessage(@RequestBody Map<String, Object> request) {
        try {
            String toUserId = (String) request.get("toUserId");
            String userName = (String) request.get("userName");
            String userRole = (String) request.get("userRole");
            
            Message message = messageService.sendWelcomeMessage(toUserId, userName, userRole);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "欢迎消息发送成功");
            response.put("data", message);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("发送欢迎消息失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "发送欢迎消息失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
    
    /**
     * 获取用户消息列表
     */
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getUserMessages(
            @RequestParam String userId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String type) {
        try {
            Page<Message> messagePage;
            
            if (type != null && !type.isEmpty()) {
                messagePage = messageService.getUserMessagesByType(userId, type, page, size);
            } else {
                messagePage = messageService.getUserMessages(userId, page, size);
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "获取消息列表成功");
            response.put("data", messagePage.getContent());
            response.put("total", messagePage.getTotalElements());
            response.put("totalPages", messagePage.getTotalPages());
            response.put("currentPage", page);
            response.put("size", size);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("获取消息列表失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "获取消息列表失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
    
    /**
     * 获取最近消息
     */
    @GetMapping("/recent")
    public ResponseEntity<Map<String, Object>> getRecentMessages(
            @RequestParam String userId,
            @RequestParam(defaultValue = "5") int limit) {
        try {
            List<Message> messages = messageService.getRecentMessages(userId, limit);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "获取最近消息成功");
            response.put("data", messages);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("获取最近消息失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "获取最近消息失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
    
    /**
     * 获取消息详情
     */
    @GetMapping("/{messageId}")
    public ResponseEntity<Map<String, Object>> getMessageById(
            @PathVariable String messageId,
            @RequestParam String userId) {
        try {
            Message message = messageService.getMessageById(messageId, userId);
            
            if (message == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 404);
                response.put("message", "消息不存在");
                return ResponseEntity.ok(response);
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "获取消息详情成功");
            response.put("data", message);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("获取消息详情失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "获取消息详情失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
    
    /**
     * 标记消息为已读
     */
    @PostMapping("/{messageId}/read")
    public ResponseEntity<Map<String, Object>> markAsRead(
            @PathVariable String messageId,
            @RequestParam String userId) {
        try {
            boolean success = messageService.markAsRead(messageId, userId);
            
            Map<String, Object> response = new HashMap<>();
            if (success) {
                response.put("code", 200);
                response.put("message", "消息已标记为已读");
            } else {
                response.put("code", 400);
                response.put("message", "标记消息已读失败");
            }
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("标记消息已读失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "标记消息已读失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
    
    /**
     * 标记所有消息为已读
     */
    @PostMapping("/read-all")
    public ResponseEntity<Map<String, Object>> markAllAsRead(@RequestParam String userId) {
        try {
            int count = messageService.markAllAsRead(userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "已标记 " + count + " 条消息为已读");
            response.put("data", count);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("批量标记消息已读失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "批量标记消息已读失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
    
    /**
     * 获取未读消息数量
     */
    @GetMapping("/unread-count")
    public ResponseEntity<Map<String, Object>> getUnreadCount(
            @RequestParam String userId,
            @RequestParam(required = false) String type) {
        try {
            long count;
            if (type != null && !type.isEmpty()) {
                count = messageService.getUnreadCountByType(userId, type);
            } else {
                count = messageService.getUnreadCount(userId);
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "获取未读消息数量成功");
            response.put("data", count);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("获取未读消息数量失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "获取未读消息数量失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
    
    /**
     * 删除消息
     */
    @DeleteMapping("/{messageId}")
    public ResponseEntity<Map<String, Object>> deleteMessage(
            @PathVariable String messageId,
            @RequestParam String userId) {
        try {
            boolean success = messageService.deleteMessage(messageId, userId);
            
            Map<String, Object> response = new HashMap<>();
            if (success) {
                response.put("code", 200);
                response.put("message", "消息删除成功");
            } else {
                response.put("code", 400);
                response.put("message", "消息删除失败");
            }
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("删除消息失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "删除消息失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
}





















